package de.bloxel.world;

import static de.bloxel.core.BloxelFactory.BloxelType.GRASS;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jme3.bounding.BoundingBox;
import com.jme3.math.Vector3f;

/**
 * Fill a {@link TerrainChunk} with a flat plane at y-level 0 over the whole area of the chunk (from -x to x and -z to
 * z).
 * 
 * @author Klaus Hauschild
 * @since 0.1.0
 */
public class PlaneTerrainLoader implements TerrainLoader {

  private static final Logger LOG = LoggerFactory.getLogger(PlaneTerrainLoader.class);

  /**
   * Each {@link TerrainElement} will have this size in x, y and z direction from the element center position.
   */
  private final Vector3f elementSize;

  /**
   * Use default element size of 0.5f in each direction.
   */
  public PlaneTerrainLoader() {
    this(Vector3f.UNIT_XYZ.mult(0.5f));
  }

  /**
   * @param theElementSize
   *          to use, each {@link TerrainElement} will have this size in x,y and z direction from the element center
   *          position
   */
  public PlaneTerrainLoader(final Vector3f theElementSize) {
    elementSize = theElementSize;
  }

  /**
   * @param theTerrainChunk
   *          to fill with {@link TerrainElement}S
   */
  @Override
  public void fill(final TerrainChunk theTerrainChunk) {
    final BoundingBox bv = theTerrainChunk.getBoundingBox();
    final float xExtent = bv.getXExtent();
    final float zExtent = bv.getZExtent();
    // final float yExtent = bv.getYExtent();
    final float startx = -xExtent + elementSize.x;
    final float endx = xExtent - elementSize.x;
    final float startz = -zExtent + elementSize.z;
    final float endz = zExtent - elementSize.z;
    final float starty = 0;
    final float endy = 0;
    final float stepx = elementSize.x * 2;
    final float stepz = elementSize.z * 2;
    final float stepy = 0;
    LOG.trace(String.format("Create plane from [x:%f,y:%f,z:%f] to [x:%f,y:%f,z:%f] use step:[x:%f,y:%f,z:%f]", startx,
        starty, startz, endx, endy, endz, stepx, stepy, stepz));
    for (float x = startx; x <= endx; x += stepx) {
      for (float z = startz; z <= endz; z += stepz) {
        final Vector3f elementCenter = new Vector3f(x, 0, z).add(bv.getCenter());
        final TerrainElement terrainElement = new TerrainElement(elementCenter, elementSize, GRASS);
        theTerrainChunk.addTerrainElement(terrainElement);
        LOG.trace(String.format("Add element %s", terrainElement));
      }
    }
  }

  @Override
  public Vector3f getElementSize() {
    return elementSize;
  }
}